package _36_两个链表的第一个公共节点;
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null ||pHead2==null) return null;
        int len1 = nodelength(pHead1);
        int len2 = nodelength(pHead2);
        int cha = Math.abs(len1-len2);

        if(len1>len2){
            while(cha>0){
                pHead1 = pHead1.next;
                cha--;
            }
        }else{
            while(cha>0){
                pHead2 = pHead2.next;
                cha--;
            }
        }
        while(pHead1!=null){
            if(pHead1.val==pHead2.val){
                return pHead1;
            }else{
                pHead1=pHead1.next;
                pHead2=pHead2.next;
            }
        }
        return null;
    }

    int nodelength(ListNode p){
        if(p==null) return 0;
        ListNode x= p;
        int count =0;
        while(x!=null){
            count++;
            x=x.next;
        }
        return count;
    }
}
